#------------------------------------------------------------------------------
# This is a shell script (for use to migrate git repo to anthor server repo)
#------------------------------------------------------------------------------

#!bin/sh

DATE=$(date "+%G-%m-%d %H:%M:%S")

function script_print()
{
	echo "[autoMigrate]:$1"
}

function script_show_version_log()
{
    echo "*********************************************************"
    echo " Copyright (c) 2015 XXXX Technology Co., Ltd. "
    echo " All rights reserved."
    echo " @File       :"
    echo " @Brief      : Auto Migrate srcIP1 "
	echo "			to dstIP2"
    echo " "
    echo " @Note       : //"
    echo " "
    echo " @Date       : $DATE"
    echo " @Author     : Mike Ross"
    echo " @Version    : 1.0.1"
    echo " History     : "
    echo " "
    echo "                 1. Setup script @2020/11/19 --lu ming liang"
    echo "                 2. Release script @2020/11/23 --lu ming liang"
    echo "**********************************************************"
    echo " "
}

function pause()
{
        read -n 1 -p "$*" INP
        if [ $INP != '' ] ; then
                echo -ne '\b \n'
        fi
}

# cloen from srcIP:xxx.git
function clone_from_srcIP_repo()
{
	git clone git@srcIP1:xxx.git	
	cd ./xxx
	git pull --all	
	git branch -r > ../branches.txt
	for line in `cat ../branches.txt`
	do
		script_print "$line"
	done
}

# Main shell 
script_show_version_log
echo ""

read -n1 -p "[autoMigrate]:Are you ready to migrate [Y/n]?" userAction
case $userAction in
y | yes | Y | YES)
	echo ""
	# Step 1, git clone old repo
	clone_from_srcIP_repo
	
	# Step 2, git change remote set-url to dstIP repo addr
	# git remote set-url origin "dstIP:xxx.git"
	for line in `cat ../branches.txt`
	do
		# Just Show line message 
		# echo "[autoMigrate]:***********************************************************************"
		# echo "[autoMigrate]:$line"
		# echo "[autoMigrate]:***********************************************************************"
		read -p "Continue to Migrate Branch (y/N)??" answer
		case $answer in 
		y | yes | Y | YES)
			# pick up string from 7th char (from left to right)
			branch_name_local=${line:7} 
			branch_name_remote_header="remotes/"
			branch_name_remote=$branch_name_remote_header$line
			script_print "$branch_name_local"
			script_print "$branch_name_remote"			
			git checkout -b $branch_name_local $branch_name_remote
			git push origin $branch_name_local:$branch_name_remote
			script_print "******Migrate branch $branch_name_local Success !!!*****"
			;;
		N | n | NO | no)
			script_print "******discard $line Branch !!!*****"
			;;
		*)
			script_print "Unspport action, quit ..."
			;;
		esac		
	done
	
	# Step 4, push all tags 
	git push origin --tags
	
	;;
N | n)
	script_print "Quit to migrate"	
	;;
*)
	script_print ":Unspport action, quit ..."
	;;
esac

script_print "Migrate Done ......"

pause '[autoMigrate]:Press any key to continue...'

exit 0
